import { STATIC_MENUS, getFilteredMenus, type MenuItem } from '@/config/menus'
import axios from 'axios'
import { defineStore } from 'pinia'

interface MenuState {
  userMenus: MenuItem[]
  userPermissions: string[]
  menuLoading: boolean
}

export const useMenuStore = defineStore('menu', {
  state: (): MenuState => ({
    userMenus: [],
    userPermissions: [],
    menuLoading: false
  }),

  getters: {
    // 获取扁平化的菜单列表（用于路由权限检查）
    flatMenus: (state): MenuItem[] => {
      const flatten = (menus: MenuItem[]): MenuItem[] => {
        let result: MenuItem[] = []
        for (const menu of menus) {
          result.push(menu)
          if (menu.children) {
            result = result.concat(flatten(menu.children))
          }
        }
        return result
      }
      return flatten(state.userMenus)
    },

    // 根据路径查找菜单项
    getMenuByPath: (state) => (path: string): MenuItem | undefined => {
      const flatten = (menus: MenuItem[]): MenuItem[] => {
        let result: MenuItem[] = []
        for (const menu of menus) {
          result.push(menu)
          if (menu.children) {
            result = result.concat(flatten(menu.children))
          }
        }
        return result
      }
      return flatten(state.userMenus).find(menu => menu.path === path)
    }
  },

  actions: {
    // 获取用户权限并生成菜单
    async loadUserMenus() {
      try {
        this.menuLoading = true

        // 从后端获取用户权限列表
        const response = await axios.get('/api/auth/permissions/')
        this.userPermissions = response.data.permissions || []

        console.log('🔑 用户权限:', this.userPermissions)
        console.log('🔑 权限类型:', response.data.user_type)

        // 基于权限过滤静态菜单
        this.userMenus = getFilteredMenus(this.userPermissions)

        console.log('📋 过滤后的菜单数量:', this.userMenus.length)
        console.log('📋 过滤后的菜单:', this.userMenus)

        return this.userMenus
      } catch (error) {
        console.error('获取用户菜单失败:', error)
        // 如果获取权限失败，使用默认菜单（仅仪表盘）
        this.userMenus = [STATIC_MENUS[0]] // 仅显示仪表盘
        this.userPermissions = ['dashboard.view']
        throw error
      } finally {
        this.menuLoading = false
      }
    },

    // 检查路径权限
    checkPathPermission(path: string): boolean {
      // 超级管理员直接通过
      if (this.userPermissions.includes('*')) {
        return true
      }

      // 查找对应的菜单项
      const menu = this.getMenuByPath(path)
      if (!menu) {
        // 如果菜单中没有定义该路径，检查是否是特殊路径
        const specialPaths = ['/dashboard', '/404', '/login', '/register']
        if (specialPaths.includes(path) || path.startsWith('/ansible') || path.startsWith('/history')) {
          return true
        }
        return false
      }

      // 检查是否有对应权限
      if (!menu.permission_code) {
        return true // 没有权限要求的菜单默认允许
      }

      return this.userPermissions.includes(menu.permission_code)
    },

    // 清理菜单数据
    clearMenus() {
      this.userMenus = []
      this.userPermissions = []
      this.menuLoading = false
    },

    // 获取所有静态菜单（用于管理界面）
    getAllStaticMenus(): MenuItem[] {
      return STATIC_MENUS
    }
  }
})
